angular.module('app').config(function ($stateProvider) {

    $stateProvider.state('app.device-motion', {
        url         : '/device-motion',
        label       : '速度传感器',
        controller  : 'app.device-motion',
        controllerAs: '$ctrl',
        templateUrl : 'view/app/device-motion/device-motion.html'
    });
}).controller('app.device-motion', function ($ionicPlatform, $timeout) {
    var ctrl = this, watchId;
    ctrl.accelerations = [];
    /**
     * Acceleration
     * - x:
     * - y:
     * - z:
     * - timestamp:
     */
    $ionicPlatform.ready(function () {
        ctrl.get = function () {
            /**
             * navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
             * 立即获取当前的加速度
             * - accelerometerSuccess: 会传入一个 Acceleration 对象的参数
             */
            navigator.accelerometer.getCurrentAcceleration(function (acceleration) {
                $timeout(function () {
                    ctrl.currentAccelerometer = acceleration;
                });
            }, onError);
        };
        ctrl.watch = function () {
            if (watchId) {
                return;
            }
            /**
             * navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, accelerometerOptions);
             * 监听设备的加速度变化
             * - accelerometerOptions
             *   - frequency: 监听频率, 默认 10000 毫秒
             * 返回一个 watchID, 可以通过 navigator.accelerometer.clearWatch(watchID) 取消监听
             */
            watchId = navigator.accelerometer.watchAcceleration(function (acceleration) {
                $timeout(function () {
                    ctrl.accelerations.unshift(acceleration);
                    if (ctrl.accelerations.length > 4) {
                        ctrl.accelerations.length = 3;
                    }
                });
            }, onError, {
                frequency: 3000
            });
        };
        ctrl.clearWatch = function () {
            if (!watchId) {
                return;
            }
            /**
             * navigator.accelerometer.clearWatch(watchID);
             * 取消监听
             */
            navigator.accelerometer.clearWatch(watchId);
            watchId = undefined;
            ctrl.accelerations.length = 0;
        };
    });

    function onError() {
        alert('onError!');
    }
});